package tu.j2ee.tasktracker.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import tu.j2ee.tasktracker.dao.CommentDAO;
import tu.j2ee.tasktracker.dao.CustomUserDAO;
import tu.j2ee.tasktracker.dao.TaskDAO;
import tu.j2ee.tasktracker.domain.Comment;
import tu.j2ee.tasktracker.domain.CustomUser;
import tu.j2ee.tasktracker.domain.Task;
import tu.j2ee.tasktracker.service.CommentService;

@RequestMapping("/comments")
@Controller
@RooWebScaffold(path = "comments", formBackingObject = Comment.class)
public class CommentController {

	@Autowired
	CommentService commentService;
	
	@Autowired
    CommentDAO commentDAO;

	@Autowired
    TaskDAO taskDAO;
	
	@Autowired
	CustomUserDAO customUserDao;
	
	@RequestMapping(value = "/forTask/{id}", method= RequestMethod.POST, produces = "application/json")
	public @ResponseBody String create(@PathVariable("id") Long forTask, @RequestParam String text){
		
		try {
			Task task = taskDAO.findOne(forTask);
			String userName = SecurityContextHolder.getContext().getAuthentication().getName();
			
			Comment comment = new Comment();
			comment.setText(text);
			comment.setTask(task);
			
			Comment save = commentService.save(comment);
			if(save != null){
				return "success";
			}else{
				return "error saving the comment to the database";
			}
		} catch (Exception e) {
			return "error" + e.getMessage();
		}
		
	}

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Comment comment, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, comment);
            return "comments/create";
        }
        uiModel.asMap().clear();
        commentService.save(comment);
        return "redirect:/comments/" + encodeUrlPathSegment(comment.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Comment());
        List<String[]> dependencies = new ArrayList<String[]>();
        if (taskDAO.count() == 0) {
            dependencies.add(new String[] { "task", "tasks" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "comments/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("comment", commentDAO.findOne(id));
        uiModel.addAttribute("itemId", id);
        return "comments/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("comments", commentDAO.findAll(new org.springframework.data.domain.PageRequest(firstResult / sizeNo, sizeNo)).getContent());
            float nrOfPages = (float) commentDAO.count() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("comments", commentDAO.findAll());
        }
        return "comments/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Comment comment, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, comment);
            return "comments/update";
        }
        uiModel.asMap().clear();
        commentDAO.save(comment);
        return "redirect:/comments/" + encodeUrlPathSegment(comment.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, commentDAO.findOne(id));
        return "comments/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Comment comment = commentDAO.findOne(id);
        commentDAO.delete(comment);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/comments";
    }

	void populateEditForm(Model uiModel, Comment comment) {
        uiModel.addAttribute("comment", comment);
        uiModel.addAttribute("tasks", taskDAO.findAll());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
